package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.HouseInfoMapper;
import com.fuego.creditsystemcommodity.service.IHouseInfoService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.HouseInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.HOUSE_INFO_STOCK_KEY;


@Service
public class HouseInfoServiceImpl extends ServiceImpl<HouseInfoMapper, HouseInfo> implements IHouseInfoService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private HouseInfoMapper houseInfoMapper;

    @Override
    public Result queryHouseInfoById(Long houseId) {
        // 查询数据库
        LambdaQueryWrapper<HouseInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HouseInfo::getHouseId, houseId);
        List<HouseInfo> houseInfos = houseInfoMapper.selectList(wrapper);

        // 如果数据为空，返回错误
        if (houseInfos == null || houseInfos.isEmpty()) {
            return Result.fail("未找到房屋信息");
        }

        // 缓存到 Redis，设置 1 小时过期时间
        for (HouseInfo houseInfo : houseInfos) {
            String key = HOUSE_INFO_STOCK_KEY + houseInfo.getHouseId() + ":" + houseInfo.getCheckinDate();
            stringRedisTemplate.opsForValue().set(key, houseInfo.getStock().toString(), 1, TimeUnit.HOURS);
        }

        // 返回结果
        return Result.ok(houseInfos);
    }
}
